/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ProductoMovimientos.java
 *
 * Created on 05/12/2010, 21:39:02
 */
package vista;

import modelo.Insumo;
import modelo.Mercaderia;
import modelo.MovimientoStock;
import modelo.Producto;
import modelo.TipoMovimiento;
import java.awt.Color;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import negocio.ExcepcionValidacion;
import negocio.FabricaNegocio;
import negocio.ServiciosNegocioProductos;

/**
 *
 * @author Aguero
 */
class ProductoMovimientos extends javax.swing.JDialog {

    private ServiciosNegocioProductos serviciosProductos;
    private Producto producto;

    /** Creates new form ProductoMovimientos */
    public ProductoMovimientos(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public ProductoMovimientos(javax.swing.JDialog parent, Mercaderia mercaderia, boolean modal) {
        super(parent, modal);
        serviciosProductos = (ServiciosNegocioProductos) FabricaNegocio.getServicioMercaderias();
        this.producto = new Mercaderia();
        this.producto = mercaderia;
        initComponents();
        actualizarTabla();
        labelNombre.setText(this.producto.getNombre());
        setLocationRelativeTo(parent);
        setVisible(true);
    }

    public ProductoMovimientos(javax.swing.JDialog parent, Insumo insumo, boolean modal) {
        super(parent, modal);
        serviciosProductos = (ServiciosNegocioProductos) FabricaNegocio.getServicioInsumos();
        this.producto = new Insumo();
        this.producto = insumo;
        initComponents();
        actualizarTabla();
        labelNombre.setText(this.producto.getNombre());
        setLocationRelativeTo(parent);
        setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaMovimientos = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        labelNombre = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        textFieldCantidad = new javax.swing.JTextField();
        dateFecha = new com.toedter.calendar.JDateChooser();
        jToolBar1 = new javax.swing.JToolBar();
        jButton2 = new javax.swing.JButton();
        labelAlerta = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Movimientos del Producto"));

        tablaMovimientos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "Fecha", "Tipo", "Cantidad"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tablaMovimientos);

        jButton3.setText("Salir");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Actualizar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        labelNombre.setFont(new java.awt.Font("Tahoma", 1, 14));
        labelNombre.setText("Producto");

        jButton1.setText("Ingreso");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton5.setText("Egreso");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jLabel1.setText("Fecha:");

        jLabel2.setText("Cantidad:");

        textFieldCantidad.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                textFieldCantidadKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(85, 85, 85)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(dateFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel2)
                        .addGap(6, 6, 6)
                        .addComponent(textFieldCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(188, 188, 188)
                        .addComponent(jButton1)
                        .addGap(25, 25, 25)
                        .addComponent(jButton5)))
                .addContainerGap(117, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2)
                        .addComponent(textFieldCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(dateFecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton5)
                    .addComponent(jButton1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jToolBar1.setRollover(true);

        jButton2.setText("Eliminar");
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton2);

        labelAlerta.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        labelAlerta.setText("jLabel3");
        labelAlerta.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButton4)
                        .addGap(140, 140, 140)
                        .addComponent(labelAlerta)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 199, Short.MAX_VALUE)
                        .addComponent(jButton3)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(labelNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(238, 238, 238))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 537, Short.MAX_VALUE)
                            .addComponent(jToolBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 537, Short.MAX_VALUE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(labelNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(9, 9, 9)
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton4)
                        .addComponent(jButton3))
                    .addComponent(labelAlerta))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
}//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        actualizarTabla();
}//GEN-LAST:event_jButton4ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        if (textFieldCantidad.getText().length() == 0) {
            Validaciones.ValidarFormularioVacio(this);

        } else {
            MovimientoStock ingreso = new MovimientoStock();
            Date fecha = dateFecha.getDate();
            ingreso.setFecha(fecha);
            ingreso.setCantidad(Integer.valueOf(textFieldCantidad.getText()));
            ingreso.setTipo(TipoMovimiento.INGRESO);
            this.producto.agregarMovimiento(ingreso);
            serviciosProductos.modificarProvMov(producto);
            actualizarTabla();
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        int fila = tablaMovimientos.getSelectedRow();
        if (fila == -1) {
            Validaciones.ValidarFilaNoSeleccionada(this);
        } else {
            
            this.producto.getMovimientos().remove(fila);
            serviciosProductos.modificarProvMov(producto);
            actualizarTabla();
        }
}//GEN-LAST:event_jButton2ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        // TODO add your handling code here:
        if (textFieldCantidad.getText().length() == 0) {
           Validaciones.ValidarFormularioVacio(this);

        } else {

            List<MovimientoStock> movimientos = (List<MovimientoStock>) this.producto.getMovimientos();
            int ingr = 0, egr = 0;
            for (MovimientoStock movimiento : movimientos) {
                if (movimiento.getTipo().compareTo(TipoMovimiento.EGRESO) == 0) {
                    egr = egr + movimiento.getCantidad();
                }
                if (movimiento.getTipo().compareTo(TipoMovimiento.INGRESO) == 0) {
                    ingr = ingr + movimiento.getCantidad();
                }

            }
            int total = ingr - egr;

            if (Integer.valueOf(textFieldCantidad.getText()) > total) {
                Validaciones.ValidarStockNegativo(this);
            } else {
                MovimientoStock ingreso = new MovimientoStock();
                Date fecha = dateFecha.getDate();
                ingreso.setFecha(fecha);
                ingreso.setCantidad(Integer.valueOf(textFieldCantidad.getText()));
                ingreso.setTipo(TipoMovimiento.EGRESO);
                this.producto.agregarMovimiento(ingreso);
                serviciosProductos.modificarProvMov(producto);
                actualizarTabla();
            }
        }
    }//GEN-LAST:event_jButton5ActionPerformed

    private void textFieldCantidadKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textFieldCantidadKeyTyped
        // TODO add your handling code here:
        Validaciones.ValidarCampoSoloNumerico(evt);
        Validaciones.LimitarCampo(evt, 4);
        Validaciones.ValidarCampoVacio(evt);
    }//GEN-LAST:event_textFieldCantidadKeyTyped

    public void actualizarTabla() {

        List<MovimientoStock> movimientos = new LinkedList();
        for (int i = 0; i < producto.getMovimientos().size(); i++) {
            movimientos.add(producto.getMovimientos().get(i));
        }

            int ingreso=0,egreso=0;
            for(MovimientoStock movimiento : movimientos){
                if(movimiento.getTipo().compareTo(TipoMovimiento.EGRESO)==0)
                    egreso=egreso+movimiento.getCantidad();
                if(movimiento.getTipo().compareTo(TipoMovimiento.INGRESO)==0)
                    ingreso=ingreso+movimiento.getCantidad();

            }
            int total=ingreso-egreso;
        if(total <= 20){
         labelAlerta.setText("Stock bajo");
         labelAlerta.setForeground(Color.red);
        }
        else{
         labelAlerta.setText("Stock normal");
         labelAlerta.setForeground(Color.green);
        }

        DefaultTableModel modeloTabla = (DefaultTableModel) tablaMovimientos.getModel();
        modeloTabla.setRowCount(0);

        for (MovimientoStock movimiento : movimientos) {
            Date date=movimiento.getFecha();
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
            String fecha = dateFormat.format(date);
            Object[] fila = {fecha, movimiento.getTipo(), movimiento.getCantidad()};
            modeloTabla.addRow(fila);
        }
    }
    /**
     * @param args the command line arguments
     */
    /* public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    ProductoMovimientos dialog = new ProductoMovimientos(new javax.swing.JFrame(), true);
    dialog.addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowClosing(java.awt.event.WindowEvent e) {
    System.exit(0);
    }
    });
    dialog.setVisible(true);
    }
    });
    }*/
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private com.toedter.calendar.JDateChooser dateFecha;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JLabel labelAlerta;
    private javax.swing.JLabel labelNombre;
    private javax.swing.JTable tablaMovimientos;
    private javax.swing.JTextField textFieldCantidad;
    // End of variables declaration//GEN-END:variables
}
